package cn.itcast.fore.action;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;
import javax.ws.rs.core.MediaType;

import org.apache.commons.lang.RandomStringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.poi.ss.formula.functions.Value;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Controller;

import cn.itcast.bos.utils.Constants;
import cn.itcast.crm.domain.Customer;
import cn.itcast.fore.utils.MailUtils;
@ParentPackage("json-default")
@Namespace("/")
@Controller
@Scope("prototype")
public class CustomerAction extends BaseAction<Customer> {
	@Autowired
	@Qualifier("jmsQueueTemplate")
	private JmsTemplate jmsTemplate;
	
	@Autowired
	private RedisTemplate<String, String> redisTemlate;
	
	@Action(value="sendSms")
	public String sendSms(){
		String telephone = model.getTelephone();
		String checkCode = RandomStringUtils.randomNumeric(4);
		ServletActionContext.getRequest().getSession().setAttribute(telephone, checkCode);
		final String content = "你好：本次注册的验证码为："+checkCode;
		
	/*	String result = SmsUtils.sendSmsByHTTP(telephone, content);
		
		if(result.startsWith("000")){
			return NONE;
		}else{
			throw new RuntimeException("短信发送错误，错误码为："+result);
		}*/
		jmsTemplate.send("bos_sms", new MessageCreator() {
			
			@Override
			public Message createMessage(Session session) throws JMSException {
				
				MapMessage mapMessage = session.createMapMessage();
				mapMessage.setString("telephone", model.getTelephone());
				mapMessage.setString("content", content);
				return mapMessage;
			}
		});
		System.out.println(content);
		return NONE;
	}
	
	private String checkCode;
	
	public void setCheckCode(String checkCode) {
		this.checkCode = checkCode;
	}


	@Action(value="customerSignUp" ,results={@Result(name="input",type="redirect",location="signup.html"),@Result(name="success",type="redirect",location="signup-success.html")})
	public String customerSignUp(){
		String sessionCheckCode = (String) ServletActionContext.getRequest().getSession().getAttribute(model.getTelephone());
		
		if(checkCode==null||!checkCode.equals(sessionCheckCode)){
			
			return INPUT;
		}else{
			
			WebClient.create("http://localhost:9999/crm_management/services/customerService/customersave").type(MediaType.APPLICATION_JSON).post(model);
			String activeCode = RandomStringUtils.randomNumeric(32);
			String content = "<h3><a href=http://localhost:9998/bos_fore/customerActive?activeCode=" + activeCode + "&telephone="+model.getTelephone()+">请于24小时内，点击下面链接地址进行激活，过期无效！</a></h3>";
			MailUtils.sendMail("速运快递注册激活邮件", content, model.getEmail());
			redisTemlate.opsForValue().set(model.getTelephone(), activeCode, 24, TimeUnit.HOURS);
			return SUCCESS;
		}
	}
	
	private String activeCode;
	
	public void setActiveCode(String activeCode) {
		this.activeCode = activeCode;
	}

	@Action(value="customerActive")
	public String customerActive() throws IOException{
		ServletActionContext.getResponse().setContentType("text/html;charset=utf-8");
		String redisActiveCode = redisTemlate.opsForValue().get(model.getTelephone());
		
		if (redisActiveCode==null||!redisActiveCode.equals(activeCode)) {
			
			ServletActionContext.getResponse().getWriter().write("激活码无效,激活失败！");
		
		}else{
			
			Customer customer = WebClient.create("http://localhost:9999/crm_management/services/customerService/findbytelephone/"+model.getTelephone()).accept(MediaType.APPLICATION_JSON)
					.get(Customer.class);
			if(customer.getType()==null||customer.getType()!=1){
				customer.setType(1);
				WebClient.create("http://localhost:9999/crm_management/services/customerService/customersave").type(MediaType.APPLICATION_JSON).post(customer);
				ServletActionContext.getResponse().getWriter().write("激活成功！");
			}else{
				
				ServletActionContext.getResponse().getWriter().write("你已经激活过了！");
			}
			
			redisTemlate.delete(model.getTelephone());
		}
		return NONE;
	}
	
	@Action(value="login",results={@Result(name="success",location="index.html#/myhome",type="redirect"),@Result(name="input",location="login.html",type="redirect")})
	public String login(){
		
		Customer customer = WebClient.create(Constants.CRM_MANAGEMENT_URL+"/services/customerService/customerlogin?telephone="+model.getTelephone()+"&password="+model.getPassword()).accept(MediaType.APPLICATION_JSON).get(Customer.class);
		
		if(customer==null){
			System.out.println("登陆失败");
			return INPUT;
		}else{
			ServletActionContext.getRequest().getSession().setAttribute("customer",customer);
			System.out.println("登陆成功");
			return SUCCESS;
		}
		
		
	}
}
